package org.jet.emall.security.filter;

import lombok.Setter;
import org.jet.emall.common.constant.CommonMapKey;
import org.jet.emall.security.token.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.util.Map;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-09 16:49
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Setter
    private JwtUtils jwtUtils;



    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(logger.isDebugEnabled()){
            logger.debug(httpServletRequest.getMethod()+"请求["+httpServletRequest.getRequestURI()+"]经过我们的token验证过滤器");
        }
        String tokenStr = httpServletRequest.getHeader(jwtUtils.getTokenHeaderName());
        if (tokenStr != null && tokenStr.startsWith(jwtUtils.getTokenHead())) {
            String token = tokenStr.substring(jwtUtils.getTokenHead().length() + 1);
            try {
                Map<String, String> claims = jwtUtils.verifyToken(token);
                Integer userId = Integer.parseInt(claims.get(CommonMapKey.USER_ID_KEY));
                String username = claims.get(CommonMapKey.USER_NAME_KEY);


                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (authentication == null) {

                    authentication = new UsernamePasswordAuthenticationToken(null, null, null);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }

                if(logger.isDebugEnabled()) {
                    logger.debug("userId["+userId+"],username["+username+"] 被放进请求Attributes中");
                }

                httpServletRequest.setAttribute(CommonMapKey.USER_ID_KEY,userId);
                httpServletRequest.setAttribute(CommonMapKey.USER_NAME_KEY,username);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);

    }
}
